﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Interactivity;
using System.Windows.Controls.Primitives;
using intera = System.Windows.Interactivity;
using MoneyBook.DialogViews;
using System.Reactive.Linq;

namespace MoneyBook.Interactivity {

    [DefaultTrigger(typeof(UIElement), typeof(System.Windows.Interactivity.EventTrigger), "MouseLeftButtonDown")]
    [DefaultTrigger(typeof(ButtonBase), typeof(System.Windows.Interactivity.EventTrigger), "Click")]
    [DefaultTrigger(typeof(Selector), typeof(System.Windows.Interactivity.EventTrigger), "SelectionChanged")]
    public class ShowDialogAction : intera.TriggerAction<DependencyObject>, INotifyActionCompleted {

        public Type DialogType {
            get { return (Type)GetValue(DialogTypeProperty); }
            set { SetValue(DialogTypeProperty, value); }
        }

        public static readonly DependencyProperty DialogTypeProperty =
            DependencyProperty.Register("DialogType", typeof(Type), typeof(ShowDialogAction), null);


        public object Parameter {
            get { return (object)GetValue(ParameterProperty); }
            set { SetValue(ParameterProperty, value); }
        }

        public static readonly DependencyProperty ParameterProperty =
            DependencyProperty.Register("Parameter", typeof(object), typeof(ShowDialogAction), null);


        protected override void Invoke(object parameter) {

            if (!this.IsExecutableType()) {
                return;
            }
            ChildWindow window = Activator.CreateInstance(this.DialogType) as ChildWindow;
            if (window == null) {
                return;
            }

            Observable.FromEventPattern(window, "Closed")
                .Where(evt => this.ActionCompleted != null && window.DialogResult.HasValue && window.DialogResult.Value)
                .Subscribe(evt => {
                    object param = window is DialogBase ? ((DialogBase)window).ResultObject : null;
                    this.ActionCompleted(this, new ActionCompletedEventArgs(param));
                });

            if (window is DialogBase) {
                ((DialogBase)window).Show(this.Parameter);
            } else {
                window.Show();
            }
            
        }

        private bool IsExecutableType() {
            if (this.DialogType == null) {
                return false;
            }
            if (!typeof(ChildWindow).IsAssignableFrom(this.DialogType)) {
                return false;
            }
            return true;

        }

        public event EventHandler<ActionCompletedEventArgs> ActionCompleted;
    }
}
